//
//  PositionTool.m
//  定位
//
//  Created by 孙鹏飞 on 2017/5/24.
//  Copyright © 2017年 homai. All rights reserved.
//

#import "PositionTool.h"
#import <CoreLocation/CoreLocation.h>

@interface PositionTool ()<CLLocationManagerDelegate,UIAlertViewDelegate>

@property (nonatomic, strong) CLLocationManager * locationManager;

@end

@implementation PositionTool
#define Isios7 [[[UIDevice currentDevice] systemVersion] floatValue] >=7
#define iOSVersion [[[UIDevice currentDevice] systemVersion] floatValue]

- (instancetype)init {
    if (self = [super init]) {
        [self getLocation];
    }
    return self;
}

- (void)getLocation
{
    // 判断定位操作是否被允许
    if([CLLocationManager locationServicesEnabled]&&([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined)) {
        //定位初始化
        _locationManager=[[CLLocationManager alloc] init];
        _locationManager.delegate= self;
        _locationManager.desiredAccuracy=kCLLocationAccuracyBest;
        _locationManager.distanceFilter = 10;
       
        if (iOSVersion>=8) {
            [_locationManager requestWhenInUseAuthorization];//使用程序其间允许访问位置数据（iOS8定位需要）
        }
        [_locationManager startUpdatingLocation];//开启定位
    }else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusRestricted) {
        //提示用户无法进行定位操作
        UIAlertView * positioningAlertivew = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"为了更好的体验,请到设置->隐私->定位服务中开启定位服务,已便获取附近信息!" delegate:self cancelButtonTitle:@"开启定位" otherButtonTitles:@"拒绝",nil];
        [positioningAlertivew show];
    }
    // 开始定位
    [_locationManager startUpdatingLocation];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)//确认跳转设置
    {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
        }
    }
    else if (buttonIndex == 1)//永不提示
    {
        //存入本地
    }
    else//残忍拒绝
    {
        //取消不做提示
    }
}

#pragma mark - CLLocationManagerDelegate
/**
 *  只要定位到用户的位置，就会调用（调用频率特别高）
 *  @param locations : 装着CLLocation对象
 */
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置，如果不想让其持续更新位置，则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
    CLLocation *currentLocation = [locations lastObject];
    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error)
     {
         if (array.count > 0)
         {
             CLPlacemark *placemark = [array objectAtIndex:0];
             //获取省份
             NSString *provice = placemark.administrativeArea;
//             NSLog(@"省份--->%@",provice);
             //获取城市
             NSString *city = placemark.locality;
             if (!city) {
                 //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                 city = placemark.administrativeArea;
             }
//             NSLog(@"城市--->%@",city);
             //获取地区
             NSString *country = placemark.subLocality;
//             NSLog(@"地区--->%@",country);
             //获取地区
             NSString *detailAddress = placemark.name;
             NSLog(@"地区--->%@",detailAddress);
             self.returnBlock(provice,city,country,detailAddress);
             
             //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
             [manager stopUpdatingLocation];
         }else if (error == nil && [array count] == 0)
         {
             NSLog(@"No results were returned.");
         }else if (error != nil)
         {
             NSLog(@"An error occurred = %@", error);
         }
     }];
}

- (void)returnLocationMessage:(ReturnLocationMessage)block
{
    self.returnBlock = block;
}

- (void)dealloc
{
    self.locationManager.delegate = nil;
}

@end
